package fn;

public class Divide extends Function {
	private static final long serialVersionUID = -4051961134970635816L;

	private Function[] child;

	private Divide(Function f0, Function f1) {
		child = new Function[] { f0, f1 };
	}

	public static Function create(Function f0, Function f1) {
		// rule 1 : numerator 0
		if (f0 instanceof Constant && ((Constant) f0).value() == 0)
			return f0;
		// rule 2 : denominator 1
		if (f1 instanceof Constant && ((Constant) f1).value() == 1)
			return f0;
		return new Divide(f0, f1);
	}

	@Override
	protected Function[] child() {
		return child;
	}

	@Override
	public double evaluate(double sub) {
		return child[0].evaluate(sub) / child[1].evaluate(sub);
	}

	@Override
	public String prefix() {
		return "\\frac{ ";
	}

	@Override
	public String infix() {
		return " }{ ";
	}

	@Override
	public String postfix() {
		return " }";
	}

	@Override
	protected int precedence() {
		return 2;
	}

	@Override
	protected boolean withPar() {
		return true;
	}

	public Function derivative() {
		Function num = Subtract.create(Multiply.create(child[0].derivative(), child[1]), Multiply.create(child[1].derivative(), child[0]));
		Function denum = Power.create(child[1], Constant.create(2));
		Function out = Divide.create(num, denum);
		return out;
	}

}
